<template>
  <view class="pages">
    <h-nav-bar fixed :title="recordType">
      <template #right>
        <u-button
          type="primary"
          @click="saveEualuation"
          shape="circle"
          text="保存"
          class="custom-style"
        ></u-button>
      </template>
    </h-nav-bar>
    <view class="maternity_name_box">
      <view class="maternity_title">产检名称</view>
      <view class="input_bg">
        <u--input
          border="none"
          type="text"
          fontSize="26rpx"
          v-model="params.name"
          customStyle="font-weight : 600"
        ></u--input>
      </view>
    </view>
    <view class="prenatal_time">
      <view class="prenatal_time_box">
        <view class="time_title">产检时间</view>
        <view class="time_box" @click="toCheckReport">
          <view class="week_time">
            <text>{{ revealVal }}</text>
            <text>{{ weeksValue }}</text>
          </view>
          <u-icon name="arrow-right" size="18" color="#333333"></u-icon>
        </view>
      </view>
    </view>
    <view class="product_box">
      <view class="product_bao">
        <view class="product_left">
          <text>产检项目</text>
          <view class="product_info">根据医生安排添加产检项目</view>
        </view>
        <view>
          <u-button
            type="primary"
            @click="
              navigateTo(`/pregnancys/index/time-table/add-product-object?ids=${productIdList}`)
            "
            shape="circle"
            text="+添加项目"
            class="addProduct"
          ></u-button>
        </view>
      </view>
      <view class="product_tag">
        <view class="product_tag_item" v-for="(item, index) in productList" :key="index">
          <up-tag
            :text="item"
            type="warning"
            bgColor="#F6F6F6"
            closeColor="#999999"
            color="#333333"
            borderColor="#F6F6F6"
            closable
            :show="showCloseBtn"
            @close="closeBtn(index)"
          ></up-tag>
        </view>
      </view>
    </view>
    <view v-if="isBianji == 1" class="bottom_btn">
      <view class="deleteProduct" @click="deleteRecord">删除本次产检</view>
    </view>
    <!-- 时间选择 -->
    <u-datetime-picker
      :formatter="formatter"
      title="请选取实际产检日期"
      :show="showDatePicker"
      v-model="newDate"
      mode="datetime"
      :maxDate="1786778555000"
      @close="showDatePicker = false"
      @cancel="showDatePicker = false"
      :closeOnClickOverlay="true"
      @confirm="onDateConfirm"
    ></u-datetime-picker>
  </view>
  <!-- 提示 -->
  <h-modal
    :show="bindShow"
    titlea="是否删除本次产检"
    leftBtn="取消"
    rightBtn="删除"
    @clear="clearEdit"
    @bind="saveEditFn"
  ></h-modal>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad, onPageScroll, onShow, onReady } from '@dcloudio/uni-app'
import { navigateBack, navigateTo, formatDate, showToast, redirectTo } from '@/utils'
import { addInspectRecord, getInspectDefault, getPrenatalExamination } from '@/api/pregnancy/index'
//周几
const newDate = ref(Date.now())
const maxDate = ref(Date.now())
//是否编辑
const isBianji = ref(0)
const showCloseBtn = ref(true)
//
const productList = ref([])
const productIdList = ref([])
//删除提示
const bindShow = ref(false)
//展示时间
const showDatePicker = ref(false)
const revealVal = ref('')
const weeks = ref(['周日', '周一', '周二', '周三', '周四', '周五', '周六'])
const weeksValue = ref('')
const recordType = ref('添加产检')
const formatter = (type, value) => {
  if (type === 'year') {
    return `${value}年`
  }
  if (type === 'month') {
    return `${value}月`
  }
  if (type === 'day') {
    return `${value}日`
  }
  return value
}
const params = ref({
  id: 0,
  name: '',
  cate_ids: [],
  date: '',
  type: 1,
})
const addItemId = ref()
const cateId = ref([])
onLoad((options) => {
  if (options.isBianji) {
    recordType.value = '编辑产检'
    addItemId.value = options.id
    params.value.type = 2
    isBianji.value = options.isBianji
    getPrenatalList()
  } else {
    getDefault()
    revealVal.value = formatDate(formatDate(), 'YYYY-MM-DD')
    let week = new Date(revealVal.value).getDay()
    weeksValue.value = weeks.value[week]
    params.value.date = `${revealVal.value} ${weeksValue.value}`
    productList.value = []
  }
  uni.$on('getProductList', (data) => {
    if (data) {
      productIdList.value = data?.paramsArr
      params.value.cate_ids = data?.paramsArr
      productList.value = data?.itemNameArr
    }
  })
})
onShow(() => {
  // if (isBianji.value == 1) {
  //   productList.value.push(...uni.getStorageSync('itemNameArr'))
  //   productList.value = [...new Set(productList.value)]
  //   productIdList.value.push(...uni.getStorageSync('paramsArr'))
  //   productIdList.value = [...new Set(productIdList.value)]
  //   params.value.cate_ids = productIdList.value
  //   // console.log( params.value.cate_ids)
  // } else {
  //   productList.value = uni.getStorageSync('itemNameArr')
  // }
})
//获取项目
function getPrenatalList() {
  getPrenatalExamination().then((res) => {
    if (res.code == 200) {
      res.data.data.forEach((item) => {
        if (addItemId.value == item.id) {
          item.user_cate.forEach((i) => {
            console.log(i.name)
            productList.value.push(i.name)
            productIdList.value.push(i.id)
            params.value.cate_ids.push(i.id)
          })
          params.value.id = item.id
          params.value.name = item.name
          revealVal.value = item.check_date
          weeksValue.value = item.week_day
          params.value.date = `${revealVal.value} ${weeksValue.value}`
        }
      })
    }
  })
}
//获取默认展示
async function getDefault() {
  const res = await getInspectDefault()
  if (res.code == 200) {
    params.value.name = res.data.data[0].add_name
  }
}
function toCheckReport() {
  showDatePicker.value = true
}
//时间选择
function onDateConfirm(e) {
  const weekselect = ['周六', '周日', '周一', '周二', '周三', '周四', '周五']
  showDatePicker.value = false
  newDate.value = e.value
  revealVal.value = formatDate(e.value, 'YYYY-MM-DD')
  let week = new Date(revealVal.value).getDay()
  weeksValue.value = weekselect[week]
  params.value.date = `${revealVal.value} ${weeksValue.value}`
  console.log(params.value.date)
}
async function saveEualuation() {
  cateId.value = productIdList.value
  if (isBianji.value == 1) {
    console.log(productIdList.value)
    if (cateId.value.length == 0) {
      showToast('请添加产检项目')
    } else {
      const res = await addInspectRecord(params.value)
      if (res.code == 200) {
        uni.removeStorageSync('paramsArr')
        uni.removeStorageSync('itemNameArr')
        showToast('编辑成功')
        navigateBack()
      }
    }
  } else {
    console.log()
    if (cateId.value.length == 0) {
      showToast('请添加产检项目')
    } else {
      params.value.cate_ids = cateId.value
      const res = await addInspectRecord(params.value)
      if (res.code == 200) {
        uni.removeStorageSync('paramsArr')
        uni.removeStorageSync('itemNameArr')
        showToast('保存成功')
        navigateBack()
      }
    }
  }
}
//关闭标签按钮
function closeBtn(e) {
  productList.value.splice(e, 1)
  productIdList.value.splice(e, 1)
  params.value.cate_ids.splice(e, 1)
}
//删除产检
async function deleteRecord() {
  bindShow.value = true
}
async function saveEditFn() {
  const res = await addInspectRecord({ id: params.value.id, type: 3 })
  if (res.code == 200) {
    bindShow.value = false
    navigateBack()
  }
}
//取消
function clearEdit() {
  bindShow.value = false
}
</script>

<style lang="scss" scoped>
.pages {
  width: 750rpx;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #f6f6f6;
  font-family: PingFang-SC-Bold, PingFang-SC;
  padding-bottom: 30rpx;
  .maternity_name_box {
    width: 702rpx;
    height: 179rpx;
    background: #ffffff;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    padding: 30rpx;
    margin-top: 30rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    .maternity_title {
      font-size: 26rpx;
      color: #333333;
      margin-bottom: 20rpx;
    }
    .input_bg {
      width: 635rpx;
      height: 59rpx;
      background: #f6f6f6;
      border-radius: 10rpx 10rpx 10rpx 10rpx;
      display: flex;
      align-items: center;
      padding: 0 20rpx;
    }
  }
  .prenatal_time {
    width: 702rpx;
    height: 110rpx;
    background: #ffffff;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    padding: 30rpx;
    margin: 30rpx 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    .prenatal_time_box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .time_title {
        font-size: 26rpx;
        color: #333333;
      }
      .time_box {
        display: flex;
        .week_time {
          font-size: 26rpx;
          color: #333333;
          margin-right: 10rpx;
          text {
            margin-left: 16rpx;
          }
        }
      }
    }
  }
  .product_box {
    width: 702rpx;
    background: #ffffff;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    padding: 30rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    .product_bao {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .addProduct {
        width: 143rpx;
        height: 46rpx;
        background: #a28aff;
        border-radius: 8rpx 8rpx 8rpx 8rpx;
        font-size: 24rpx;
      }
      .product_left {
        font-size: 26rpx;
        color: #333333;
        .product_info {
          color: #999999;
          margin-top: 10rpx;
        }
      }
    }
  }
  .bottom_btn {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 750rpx;
    height: 147rpx;
    background: #ffffff;
    box-shadow: 0rpx 4rpx 4rpx 9rpx rgba(226, 226, 226, 0.25);
    border-radius: 0rpx 0rpx 0rpx 0rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .deleteProduct {
      width: 580rpx;
      height: 76rpx;
      background: #ffffff;
      border-radius: 341rpx 341rpx 341rpx 341rpx;
      border: 2rpx solid #8e70ff;
      font-weight: 600;
      font-size: 32rpx;
      color: #8e70ff;
      text-align: center;
      line-height: 76rpx;
    }
  }
}
//nav
.custom-style {
  width: 102rpx;
  height: 46rpx;
  background: #a28aff;
  border-radius: 69rpx 69rpx 69rpx 69rpx;
}
.product_tag {
  display: flex;
  flex-wrap: wrap;
}
</style>
